
import 'dart:io';

import 'package:ceramics/util/ab_loading.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_luban/flutter_luban.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class VideoObject {
  final String path;
  final Uint8List? thumb;
  VideoObject(this.path,this.thumb);
}

Future<String> selectPhoto(BuildContext context) async {
  ImageSource? result = await showModalBottomSheet(context: context,
      backgroundColor: Colors.transparent,
      builder: (ctx){
    return const SelectPhotoSheet();
  });
  ImagePicker picker = ImagePicker();

  if (result != null) {
    try {
      if (result == ImageSource.camera) {
        var permission = await Permission.camera.request();
        if (permission != PermissionStatus.granted) {
          showCupertinoDialog(context: Get.context!, builder: (ctx){
            return CupertinoAlertDialog(
              title: const Text('Permission required'),
              content: const Text('Please allow camera permission'),
              actions: [
                CupertinoDialogAction(child: const Text('Cancel'),onPressed: (){
                  Navigator.pop(context);
                }),
                CupertinoDialogAction(
                  child: const Text('OK'),
                  onPressed: (){
                    Navigator.pop(context);
                    openAppSettings();
                  },
                )
              ],
            );
          });
          return "";
        }
      } else if (result == ImageSource.gallery) {
        var permission = await Permission.photos.request();
        if (permission != PermissionStatus.granted) {
          showCupertinoDialog(context: Get.context!, builder: (ctx){
            return CupertinoAlertDialog(
              title: const Text('Permission required'),
              content: const Text('Please allow photo permission'),
              actions: [
                CupertinoDialogAction(child: const Text('Cancel'),onPressed: (){
                  Navigator.pop(context);
                }),
                
                CupertinoDialogAction(
                  child: const Text('OK'),
                  onPressed: (){
                    Navigator.pop(context);
                    openAppSettings();
                  },
                )
              ],
            );
          });
          return "";
        }
      }

      var pickedFile = await picker.pickImage(source: result);
      // get file name
      var fileName = pickedFile!.path.split("/").last;
      // copy file to cache directory
      var directory = await getTemporaryDirectory();
      var path = "${directory.path}/$fileName";
      await pickedFile.saveTo(path);
      dismissLoading();
      return path;
    // return await uploadFile(compressedPath) ?? "";
    } catch (e) {
      // toast('Failed to upload image');
    }
  }
  return "";
}

Future<VideoObject> selectVideo(BuildContext context) async {
  var result = await showModalBottomSheet(context: context,
      backgroundColor: Colors.transparent,
      builder: (ctx){
        return const SelectPhotoSheet();
      });
  ImagePicker picker = ImagePicker();
  if (result != null) {
    var pickedFile = await picker.pickVideo(source: result);
    var fileName = pickedFile!.path.split("/").last;
    var directory = await getTemporaryDirectory();
    var path = "${directory.path}/$fileName";
    // var thumb = await VideoThumbnail.thumbnailData(
    //   video: pickedFile.path,
    //   imageFormat: ImageFormat.JPEG,
    //   maxWidth: 100, // specify the width of the thumbnail, let the height auto-scaled to keep the source aspect ratio
    //   quality: 25,
    // );
    return VideoObject(pickedFile.path, Uint8List(10));
    // return await uploadFile(compressedPath) ?? "";
  }
  return VideoObject('', Uint8List(0));
}

class SelectPhotoSheet extends StatelessWidget {
  const SelectPhotoSheet({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(26)),
      ),
      clipBehavior: Clip.hardEdge,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
              width: double.infinity,
              child: ElevatedButton(onPressed: (){
                Navigator.pop(context, ImageSource.gallery);
              },style: ElevatedButton.styleFrom(
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                backgroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(0),
                ),
                padding: const EdgeInsets.symmetric(vertical: 16),
              ), child: const Text('Album',style: TextStyle(color: Colors.black87,fontSize: 18)))),
          Divider(height: 0.5,color: Colors.white.withOpacity(0.5)),
          SizedBox(
              width: double.infinity,
              child: ElevatedButton(onPressed: (){
                Navigator.pop(context, ImageSource.camera);
              },style: ElevatedButton.styleFrom(
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                backgroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(0),
                ),
                padding: const EdgeInsets.symmetric(vertical: 16),
              ), child: const Text('Camera',style: TextStyle(color: Colors.black87,fontSize: 18)))),
          Divider(height: 0.5,color: Colors.white.withOpacity(0.5)),
          SizedBox(
              width: double.infinity,
              child: ElevatedButton(onPressed: (){
                Navigator.pop(context);
              },style: ElevatedButton.styleFrom(
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                backgroundColor: Colors.white,
                elevation: 0,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(0),
                ),
                padding: const EdgeInsets.symmetric(vertical: 16),
              ), child: const Text('Cancel',style: TextStyle(color: Color(0xFFF96161),fontSize: 18)))),
          SizedBox(height: MediaQuery.of(context).padding.bottom)
        ],
      ),
    );
  }
}

